<template>
  <div class="card">
    <el-input style="width: 240px" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
    <el-button type="primary" style="margin-left: 5px" @click="load">查询</el-button>
    <el-button type="warning" style="margin-left: 5px" @click="reset">清空</el-button>
  </div>
  <div class="card">
    <el-button type="primary" style="margin-left: 5px" @click="handleAdd">新增</el-button>
    <el-button type="danger" style="margin-left: 5px" @click="deleteBatch">批量删除</el-button>
  </div>
  <div class="card">
    <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        border
    >
      <!-- 基础信息列 -->
      <el-table-column prop="productName" label="商品名称" width="100"/>

      <!-- 分类与品牌列 -->
      <el-table-column prop="categoryName" label="商品分类" width="100">
        <!-- 分类字段说明：实际开发中可通过字典表映射显示值 -->
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="brandName" label="品牌" width="120"/>

      <!-- 规格与价格列 -->
      <el-table-column prop="specification" label="规格" width="100"/>
      <el-table-column prop="purchasePrice" label="进货价" width="100">
        <template #default="scope">
          {{ scope.row.purchasePrice }} 元
        </template>
      </el-table-column>
      <el-table-column prop="sellingPrice" label="销售价" width="100">
        <template #default="scope">
          {{ scope.row.sellingPrice }} 元
        </template>
      </el-table-column>

      <!-- 库存与保质期列 -->
      <el-table-column prop="stockQuantity" label="库存数量" width="90">
        <template #default="scope">
      <span :class="scope.row.stockQuantity < 10 ? 'low-stock' : ''">
        {{ scope.row.stockQuantity }}
      </span>
        </template>
      </el-table-column>
      <el-table-column prop="expiryDate" label="保质期" width="140">
        <template #default="scope">
          {{ formatDate(scope.row.expiryDate) }}
        </template>
      </el-table-column>

      <!-- 图片列 -->
      <el-table-column label="商品图片" width="180">
        <template #default="scope">
          <el-image
              :src="scope.row.imagePath"
              fit="cover"
              width="100px"
              height="60px"
              :preview-src-list="[scope.row.imagePath]"
          />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change = "load"
        @current-change = "load"
        style="margin-top: 10px"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="[5, 10, 15, 20]"
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        :total="data.total" />
  </div>
  <div>
    <el-dialog title="新增管理员信息" v-model="data.formVisible"  width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" style="margin:10px">
        <el-form-item label="账号" :label-width="80" prop="username">
          <el-input v-model="data.form.username" autocomplete="off" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item label="姓名" :label-width="80" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入姓名"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref, reactive} from "vue"
import {Delete, Edit, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  name:null,
  tableData:[],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible:false,
  form:{},
  ids:[],
  rules:{
    //姓名是必填的，当未填写而鼠标失焦（blur）时，会弹出提示信息：请输入账号
    username :[
      {required:true,message:'请输入账号',trigger:'blur'}
    ],
    name :[
      {required:true,message:'请输入名称',trigger:'blur'}
    ],
  }
})
const formRef = ref()
const load = ()=>{
  request.get("admin/selectPage",{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name,
    }
  }).then(res =>{
    data.tableData=res.data.list
    data.total = res.data.total
    console.log(res.data)
  })
}

const reset = ()=>{
  data.name = null
  console.log("clear")
  load()
}
const handleAdd =()=>{
  data.formVisible=true;
  data.form={}
}
const save =()=>{
  formRef.value.validate((valid)=>{
    if(valid){
      data.form.id?update():add();
    }
  })


}
const add=()=>{
  //数据中没有id
  request.post("/admin/add",data.form).then(res=>{
    if(res.code === '200'){
      data.formVisible=false;
      ElMessage.success("操作成功");
      load();  //新增后重新加载数据
    }else{
      ElMessage.error(res.msg);
    }
  })
}
const update=()=>{
  //数据中带有id
  request.put("/admin/update",data.form).then(res=>{
    if(res.code === '200'){
      data.formVisible=false;
      ElMessage.success("操作成功");
      load();  //更新后重新加载数据
    }else{
      ElMessage.error(res.msg);
    }
  })
}

const HandleUpdate=(row)=>{
  data.form=JSON.parse(JSON.stringify(row));//深拷贝，不要影响原数据
  data.formVisible=true;
}
const HandleDelete=(id)=>{
  ElMessageBox.confirm('删除后数据无法恢复，你确认删除吗','删除确认',{ type:'warning'}).then(()=>{
    request.delete('admin/delete/'+id).then(res=>{
      if(res.code === '200'){
        data.formVisible=false;
        ElMessage.success("操作成功");
        load();  //删除后重新加载数据
      }else{
        ElMessage.error(res.msg);
      }
    })
  }).catch()
}

const handleSelectionChange=(rows)=>{  //返回所有选中的行对象数组
  //从选中的行对象数组中取出所有的id组成一个新的数组
  data.ids = rows.map(row => row.id);
}
const deleteBatch=()=> {
  if (data.ids.length === 0) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，你确认删除吗', '删除确认', {type: 'warning'}).then(() => {
    request.delete("admin/deleteBatch",{ data: data.ids}).then(res=>{
      if(res.code === '200'){
        data.formVisible=false;
        ElMessage.success("操作成功");
        load();  //批量删除后重新加载数据
      }else{
        ElMessage.error(res.msg);
      }
    })
  }).catch()
}

load()
</script>

